$(function () {
    var showType = true;
    var listParam = {
        carAuthState:clientCommon.getUrlParam('carAuthState') || '',//启辕认证,
        brandId:clientCommon.getUrlParam('brandId') || '',//品牌Id
        carEnviron:'',//环保等级
        carOutColor:'',//车身颜色
        carSaleState:20,//上架状态 0 初始化 10 申请上架 20 上架 30 下架
        carTypeId:clientCommon.getUrlParam('carTypeId') || '',//车身类型
        fromCarAge:clientCommon.getUrlParam('fromCarAge') || '',//车龄（起）
        toCarAge:clientCommon.getUrlParam('toCarAge') || '',//车龄（止）
        fromMileage:clientCommon.getUrlParam('fromMileage') || '',//行驶里程，万公里（起）
        toMileage:clientCommon.getUrlParam('toMileage') || '',//行驶里程，万公里（止）
        fromRetailPrice:clientCommon.getUrlParam('fromRetailPrice') || '',//零售价底价
        toRetailPrice:clientCommon.getUrlParam('toRetailPrice') || '',//零售价底价（止）
        carGearbox: '',//变速箱
        marketId:1,//市场ID
        orderColunm:'',//排序字段
        orderMode:'ASC',//排序方式（升序：ASC，降序：DESC）
        seriesId:'',//车系ID
        carDisplacementFrom:'',//排量起
        carDisplacementTo:'',//排量止
        chioceSuv:Boolean(clientCommon.getUrlParam('chioceSuv')),
        pageIndex:1,
        pageSize:40,
        'model.modelSeat':'',
    };

    //回填首页筛选条件
    function getParams(){
        if(clientCommon.getSession('hot-condition')){
            var key = clientCommon.getSession('hot-condition').split('=')[0];
            var value = clientCommon.getSession('hot-condition').split('=')[1];
            switch (key){
                case 'brandId':
                    $("#hotBrandList span[id =" + value + "]").css({'background':'#FF6C00','color':'#fff'});
                    break;
                case 'carTypeId':
                    $("#carType").val(value);
                    $("#no-limit").css({'background':'#fff','color':'#333'});
                    break;
                case 'carMileageId':
                    var data;
                    switch (value) {
                        case '1':
                            data = "0-1";
                            break;
                        case '2':
                            data = "1-3";
                            break;
                        case '3':
                            data = "3-5";
                            break;
                        case 4:
                            data = "5-8";
                            break;
                        case 5:
                            data = "8-10";
                            break;
                        case 6:
                            data = "10-100";
                            break;
                    }
                    $("#carMile").val(data);
                    $("#no-limit").css({'background':'#fff','color':'#333'});
                    break;
                case 'yearId':
                    var year;
                    switch (value) {
                        case '1':
                            year = "0-1";
                            break;
                        case '2':
                            year = "1-3";
                            break;
                        case '3':
                            year = "3-5";
                            break;
                        case '4':
                            year = "5-8";
                            break;
                    }
                    $("#carAge").val(year);
                    $("#no-limit").css({'background':'#fff','color':'#333'});
                    break;
                case 'priceId':
                    var price;
                    switch (value) {
                        case '1':
                            price = "0-3";
                            break;
                        case '2':
                            price = "3.01-5";
                            break;
                        case '3':
                            price = "5.01-10";
                            break;
                        case '4':
                            price = "10.01-15";
                            break;
                        case '5':
                            price = "15.01-20";
                            break;
                        case '6':
                            price = "20.01-30";
                            break;
                        case '7':
                            price = "30.01-50";
                            break;
                        case '8':
                            price = "50.01-9999.99";
                            break;
                    }
                    $("#price span[id =" + JSON.stringify(price) + "]").css({'background':'#FF6C00','color':'#fff'});
                    $("#price-limit").css({'background':'#fff','color':'#333'});
                    break;
            }
        }
    }

    _getBaseDate.getCarListNumber(getAllNumbers,{marketId:1,carSaleState:20});
    function getAllNumbers(list) {
        $('#car-numbers').text('全国有' + list + '辆车')
    }
    //渲染列表
    function renderList(){
        listParam.pageIndex = 1;
        _getBaseDate.getCarListNumber(renderPage,listParam);
        _getBaseDate.getCarList(renderCarList,listParam,renderSortCarList);
    }
    //渲染品牌列表
    _getBaseDate.getGroupBrandList();
    function renderBrandList(list,letter){
        for(var i=0;i<list.length;i++){
            if(list[i].initial == letter){
                for(var j=0;j<list[i].brandInfo.length;j++){
                    $('#brandList').append('<span id="' + list[i].brandInfo[j].brandId +'">' + list[i].brandInfo[j].brandName + '</span>')
                }
            }
        }
    }
    //选择品牌
    $('.no-limit').on('click',function () {
        $(this).parent().next().hide();
        $(this).parent().next().next().show();
    });
    $('#brand a').on('click',function () {
        $(this).css({'background':'#FF6C00','color':'#fff'});
        $(this).siblings().css({'background':'#fff','color':'#333'});
        $(this).parent().parent().parent().css("height","68px");
        $('.all').show();
        $('.sub').hide();
        $('#carSeries').empty();
        $('#series').css("height",$('#series').height());
        if($(this).text()!='热门'){
            $('#brandList').empty();
            $('#hotBrandList').hide();
            $('#brandList').show();
            if(clientCommon.getSession('groupBrandList')){
                renderBrandList(JSON.parse(clientCommon.getSession('groupBrandList')),$(this).text())
            }else{
                _getBaseDate.getGroupBrandList(renderBrandList,$(this).text());
            }
        }else{
            $('#brandList').empty();
            $('#hotBrandList').show();
            $('.sub-type span').css({'background':'#fff','color':'#333'});
            listParam.seriesId = '';
            listParam.brandId = '';
            _getBaseDate.getCarList(renderCarList,listParam,renderSortCarList);
        }
    });
    $('.sub-type').on('click','span',function () {
        $('#all').show();
        $('#sub').hide();
        $('#series').css("height",'68px');
        $(this).css({'background':'#FF6C00','color':'#fff'});
        $(this).siblings().css({'background':'#fff','color':'#333'});
        _getBaseDate.getSeriesList(renderSeriesList,{brandId:$(this).attr('id')});
        listParam.brandId = $(this).attr('id');
        listParam.seriesId = '';
        renderList()
    });
    //渲染车系
    function renderSeriesList(list){
        $('#carSeries').empty();
        for (var i=0;i<list.length;i++){
            $('#carSeries').append('<span id="' + list[i].seriesId +'">' + list[i].seriesName + '</span>')
        }
        //选择车系
        $('#age span').on('click',function () {
            $(this).css({'background':'#FF6C00','color':'#fff'});
            if($(this).text()!='不限'){
                $(this).parent().siblings().css({'background':'#fff','color':'#333'});
                $(this).siblings().css({'background':'#fff','color':'#333'});
            }else{
                $(this).siblings().children().css({'background':'#fff','color':'#333'});
            }
            listParam.seriesId = $(this).attr('id');
            renderList()
        });
    }
    //价格
    function renderPriceList(list){
        for (var i=0;i<list.length;i++){
            $('#price').append('<span id="' + list[i].priceFrom10000 + '-' + list[i].priceTo10000 +'">' + list[i].priceRemark + '</span>')
        }
        getParams();
        //选择价格
        $('#price span').on('click',function () {
            $(this).css({'background':'#FF6C00','color':'#fff'});
            $(this).siblings().css({'background':'#fff','color':'#333'});
            if($(this).attr('id')==undefined){
                listParam.fromRetailPrice = '';
                listParam.toRetailPrice = '';
            }else{
                listParam.fromRetailPrice = $(this).attr('id').split('-')[0];
                listParam.toRetailPrice = $(this).attr('id').split('-')[1];
            }
            renderList()
        });
    }
    _getBaseDate.getPriceList(renderPriceList);
    //输入价格查询车辆
    $('#ensure').on('click',function () {
        listParam.fromRetailPrice = $('#startPrice').val();
        listParam.toRetailPrice = $('#endPrice').val();
        renderList()
    });
    //控制输入的必须是数字
    $('.price-load').on('input',function () {
        if(isNaN(Number($(this).val()))){
            $(this).val('')
        }
    });
    //车身类型
    function renderCarTypeList(list){
        for (var i=0;i<list.length;i++){
            $('#carType').append('<option value="' + list[i].carTypeId +'">' + list[i].carTypeName + '</option>')
        }
        getParams();
    }
    $('#carType').on('change',function () {
        listParam.carTypeId = $(this).val();
    });
    _getBaseDate.getCarTypeList(renderCarTypeList);
    //颜色
    function renderColorList(list){
        for (var i=0;i<list.length;i++){
            $('#carColor').append('<option value="' + list[i].colorName +'">' + list[i].colorName + '</option>')
        }
    }
    $('#carColor').on('change',function () {
        listParam.carOutColor = $(this).val();
    });
    _getBaseDate.getColorList(renderColorList);
    //车龄
    $('#carAge').on('change',function () {
        listParam.fromCarAge = $(this).val().split('-')[0];
        listParam.toCarAge = $(this).val().split('-')[1];
    });
    //里程
    function renderCarMileList(list){
        for (var i=0;i<list.length;i++){
            var data = [list[i].carMileageFrom,list[i].carMileageTo].join('-');
            $('#carMile').append('<option  value="' + data +'">' + list[i].carMileageRemark + '</option>')
        }
        getParams()
    }
    $('#carMile').on('change',function () {
        listParam.fromMileage = $(this).val().split('-')[0];
        listParam.toMileage = $(this).val().split('-')[1];
    });
    _getBaseDate.getCarMileageList(renderCarMileList);
    //环保等级
    $('#carTurStand').on('change',function () {
        listParam.carEnviron = $(this).val();
    });
    //变速箱
    $('#gearbox').on('change',function () {
        listParam.carGearbox = $(this).val();
    });
    //车辆用途
    $('#carUse').on('change',function () {
        listParam.carPurpose = $(this).val();
    });
    //燃料类型
    $('#flueType').on('change',function () {
        listParam.carFuel = $(this).val();
    });
    //座位数
    $('#seatNumber').on('change',function () {
        listParam['model.modelSeat'] = $(this).val();
    });
    //进气方式
    $('#carTur').on('change',function () {
        listParam.carInletModel = $(this).val();
    });
    //排量
    $('#turbo').on('change',function () {
        listParam.carDisplacementFrom = $(this).val().split('-')[0];
        listParam.carDisplacementTo = $(this).val().split('-')[1];
    });
    $(".other-condition").on('change',function () {
        renderList();
        $('#no-limit').css({'background':'#fff','color':'#333'})
    });
    //其他不限清空数据
    $('#no-limit').on('click',function () {
        $(this).css({'background':'#FF6C00','color':'#fff'});
        listParam.carInletModel = '';
        listParam['model.modelSeat'] = '';
        listParam.carFuel = '';
        listParam.carGearbox = '';
        listParam.fromMileage = '';
        listParam.toMileage = '';
        listParam.carPurpose = '';
        listParam.carTypeId= '';
        listParam.fromCarAge = '';
        listParam.toCarAge = '';
        listParam.fromRetailPrice = '';
        listParam.toRetailPrice = '';
        listParam.carOutColor = '';
        listParam.carEnviron = '';
        listParam.carDisplacementFrom = '';
        listParam.carDisplacementTo = '';
        $(".other-condition").val("");
        renderList();
    });
    //收起全部
    $('.all').on('click',function () {
        $(this).parent().parent().parent().parent().css("height","auto");
        $(this).hide();
        $(this).siblings().show();
        $(this).parent().parent().parent().siblings().css("height",$(this).parent().parent().parent().parent().height())//左侧高度设置;
    });
    $('.sub').on('click',function () {
        $(this).parent().parent().parent().parent().css("height","68px");
        $(this).hide();
        $(this).siblings().show();
        $(this).parent().parent().parent().siblings().css("height",$(this).parent().parent().parent().parent().height());//左侧高度设置;
    });
    //初始渲染车辆列表
    function renderCarList(list){
        $('#car-List').empty();
        if(list.length == 0){
            $('#car-List').append('<div class="default-page"><img src="../../images/default.png"><p>暂无符合条件车款，您可添加订阅！</p></div>');
            return false
        }
        var p,validateImg;
        for(var i=0;i<list.length;i++){
            list[i].carLicenceDate = clientCommon.checkValue(list[i].carLicenceDate);
            list[i].carMileage = clientCommon.checkValue(list[i].carMileage);
            list[i].carTitle = clientCommon.checkValue(list[i].carTitle);
            list[i].carRetailPrice = clientCommon.checkValue(list[i].carRetailPrice);
            list[i].carLicenceDate = clientCommon.handleDate('yyyy-MM',list[i].carLicenceDate);
            if(list[i].carAuthState == 10){
                validateImg = '<img class="QY-validate-img" src="../../images/认证icon04@2x.png">';
            }else{
                validateImg = ''
            }
            if(list[i].carRetailPrice == '--'||list[i].carRetailPrice == 0){
                p1 = '<p class="car-item-price item-common">' + "面议" + validateImg + '</p>';
            }else{
                p1 = '<p class="car-item-price item-common"><span>￥</span>' + list[i].carRetailPrice + "万元" + validateImg + '</p>'
            }
            if(list[i].carLicenceState == 1){
                p = '<p class="car-sub-info item-common">' + list[i].carLicenceDate + "上牌 " + list[i].carMileage + "万公里" + '</p>'
            }else if(list[i].carLicenceState == 3){
                p = '<p class="car-sub-info item-common">' + "新车 " + list[i].carMileage + "万公里" + '</p>'
            }else{
                p = '<p class="car-sub-info item-common">' + "未上牌 " + list[i].carMileage + "万公里" + '</p>'
            }
            $('#car-List').append('<a data-id="' + list[i].carId + '" class="car-item"><div class="car-item-box">\n' +
                '<img src="' + imageUrl + list[i].carImageUrl + '.r_290xh_230' + '">\n' +
                '<p class="car-info item-common ">' + list[i].carTitle + '</p>\n' + p + p1 +
                '</div></a>');
        }
        $('.car-item').on('click',function () {
            window.open('../../html/list/list-detail.html?carId=' + $(this).attr('data-id'));
        });
    }
    //列表
    function renderSortCarList(list){
        $('#sort-List').empty();
        if(list.length == 0){
            $('#sort-List').append('<div class="default-page"><img src="../../images/default.png"><p>暂无符合条件车款，您可添加订阅！</p></div>');
            return false
        }
        var p,span;
        for(var i=0;i<list.length;i++){
            list[i].carTitle = clientCommon.checkValue(list[i].carTitle);
            list[i].carLicenceDate = clientCommon.checkValue(list[i].carLicenceDate);
            list[i].shop.shopName = clientCommon.checkValue(list[i].shop.shopName);
            list[i].carMileage = clientCommon.checkValue(list[i].carMileage);
            list[i].carGearbox = clientCommon.checkValue(list[i].carGearbox);
            list[i].shop.market.city.cityName = clientCommon.checkValue(list[i].shop.market.city.cityName);
            list[i].carLicenceDate = clientCommon.handleDate('yyyy-MM',list[i].carLicenceDate);
            if(list[i].carRetailPrice == '--'||list[i].carRetailPrice == 0||!list[i].carRetailPrice){
                p = '<p class="price">面议</p>';
            }else{
                p = '<p class="price"><span>￥</span>' + list[i].carRetailPrice + '万元</p>'
            }
            if(list[i].carLicenceState == 1){
                span = '<span><a>'+ list[i].carLicenceDate + '</a><a class="a-bottom">上牌</a></span>'
            }else if(list[i].carLicenceState == 3){
                span = '<span><a>'+ "新车" + '</a><a class="a-bottom">--</a></span>'
            }else{
                span = '<span><a>'+ "未上牌" + '</a><a class="a-bottom">--</a></span>'
            }
            $('#sort-List').append('<div data-id="' + list[i].carId + '" class="car-list-item">\n' +
                '                    <img src="' + imageUrl + list[i].carImageUrl + '.r_290xh_230' + '">\n' +
                '                    <div class="item-right-box">\n' +
                '                        <h4>' + list[i].carTitle + '</h4>\n' +
                '                        <p class="QY-validate" show="'+ list[i].carAuthState +'">\n' +
                '                            <img src="../../images/认证icon04@2x.png">\n' +
                '                        </p>\n' +
                '                        <p class="car-item-detail">\n' + span +
                '                            <img class="line" src="../../images/line.png">\n' +
                '                            <span class="span-margin-left">\n' +
                '                                <a>' + list[i].carMileage + '</a>\n' +
                '                                <a class="a-bottom">表显里程</a>\n' +
                '                            </span>\n' +
                '                            <img class="line" src="../../images/line.png">\n' +
                '                            <span class="span-margin-left">\n' +
                '                                <a>' + list[i].carGearbox + '</a>\n' +
                '                                <a class="a-bottom">变速箱</a>\n' +
                '                            </span>\n' +
                '                            <img class="line" src="../../images/line.png">\n' +
                '                            <span class="span-margin-left">\n' +
                '                                <a>' + list[i].shop.market.city.cityName + '</a>\n' +
                '                                <a class="a-bottom">所在城市</a>\n' +
                '                            </span>\n' + p +
                '                        </p>\n' +
                '                    </div>\n' +
                '                </div>');
        }
        $(".QY-validate[show!='10']").hide();
        $('.car-list-item').on('click',function () {
            window.open('../../html/list/list-detail.html?carId=' + $(this).attr('data-id'));
        })
    }
    //获取车辆列表数据
    renderList();
    $('.rectangle').on('click',function () {
        showType = true;
        $('.car-list').css('height',$("#car-List").height() + 10);
        $(this).attr('src','../../images/rectangle-act.png');
        $('.list-sort').attr('src','../../images/list.png');
        $('#car-List').show();
        $('#sort-List').hide();

    });
    //切换排列方式
    $('.list-sort').on('click',function () {
        showType = false;
        $('.car-list').css('height',$("#sort-List").height() + 10);
        $(this).attr('src','../../images/list-act.png');
        $('.rectangle').attr('src','../../images/rectangle.png');
        $('#car-List').hide();
        $('#sort-List').show();
    });
    //排序
    $('.tab-sort span').on('click',function () {
        $(this).attr('class','active-bg type-border');
        $(this).siblings().attr('class','type-border');
        listParam.orderColunm = $(this).attr('data-sort').split(',')[0];
        listParam.pageIndex = 1;
        listParam.orderMode = $(this).attr('data-sort').split(',')[1];
        _getBaseDate.getCarListNumber(renderPage,listParam);
        _getBaseDate.getCarList(renderCarList,listParam,renderSortCarList);
    });
    //调起分页插件
    function renderPage(data){
        if(data == 0){
            $('#PageNavId').hide();
            return false
        }else{
            $('#PageNavId').show();
            data = parseInt((data % 40) == 0  ? (data / 40) :(data / 40) + 1);
            clientCommon.setSession('LIST_TOTAL_PAGE',data);
            pageNavObj = new PageNavCreate("PageNavId",{
                pageCount:data,//总页数
                currentPage:1,//当前页
                perPageNum:5,//每页按钮数
            });
            pageNavObj.afterClick(pageNavCallBack);
        }
    }

    function pageNavCallBack(clickPage){
        listParam.pageIndex = clickPage;
        _getBaseDate.getCarList(renderCarList,listParam,renderSortCarList);
        pageNavObj = new PageNavCreate("PageNavId",{
            pageCount:getPageSet().pageCount,//总页数
            currentPage:clickPage,//当前页
            perPageNum:getPageSet().perPageNum,//每页按钮数
        });
        pageNavObj.afterClick(pageNavCallBack);
    }
    function getPageSet(){
        var obj = {
            pageCount:null,//总页数
            currentPage:null,//当前页
            perPageNum:null,//每页按钮数
        };
        obj.pageCount = parseInt(clientCommon.getSession('LIST_TOTAL_PAGE'));
        obj.currentPage = 1;
        obj.perPageNum = null;

        return obj;
    }
});